package reduce.fz.com.reduce.util;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.LruCache;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.util.base.FileCache;
import reduce.fz.com.reduce.util.http.BitmapLruCache;
import reduce.fz.com.reduce.util.http.ImageLoader;
import reduce.fz.com.reduce.util.http.ReduceRequest;

/**
 * Created by qingshengzheng on 15/7/8.
 */
public class HttpUtils {
    private final static String HTTP_PREFIX = "http://";
    private final static String HTTPS_PREFIX = "https://";

    //http请求队列
    private static RequestQueue mRequestQueue;
    //网络图片请求队列
    private static RequestQueue mImageRequestQueue;
    //sd卡图片加载器
    private static SDCardImageLoader mSDCardImageLoader;
    //图片LRU缓存
    private static BitmapLruCache mBitmapLruCache;
    //图片加载器
    private static ImageLoader mImageLoader;
    //头像加载器
    private static ImageLoader mAvatarImageLoader;
    //硬盘缓存
    private static DiskLruCache mDiskLruCache;
    //内存缓存
    private static LruCache<String, Bitmap> mMemoryCache;
    public static String request_domain = null;

    static {
        request_domain = "http://123.57.205.140:8080/";
    }

    public static ImageLoader getImageLoader() {
        if (null != mImageLoader) {
            return mImageLoader;
        } else {
            throw new IllegalStateException("ImageLoader not initialized");
        }
    }

    public static ImageLoader getAvatarImageLoader() {
        return mAvatarImageLoader;
    }

    /**
     * JSON post请求
     *
     * @param url
     * @param requestBody
     * @param response
     */
    public static void jsonPost(String url,
                                Object requestBody, AbResponseListener response) {
        RequestQueue queue = getRequestQueue();
        JsonRequest request = new JsonRequest(Request.Method.POST, prefixUrl(url), JsonUtil.convertToString(requestBody), response, response);
        queue.add(request);
    }

    /**
     * 普通get请求
     *
     * @param url
     * @param response
     */
    public static void get(String url,
                           AbResponseListener response) {
        RequestQueue queue = getRequestQueue();
        queue.add(new ReduceRequest(prefixUrl(url), response, response));
    }

    public static String prefixUrl(String url) {
        String turl = url;
        if (!(url.startsWith(HTTP_PREFIX) || url.startsWith(HTTPS_PREFIX))) {
            turl = request_domain + url;
        }
        return turl;
    }

    /**
     * post请求
     *
     * @param url
     * @param params
     * @param response
     */
    public static void post(String url, final HashMap params, AbResponseListener response) {

        RequestQueue queue = getRequestQueue();
        ReduceRequest request = new ReduceRequest(Request.Method.POST, prefixUrl(url), response, response) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        queue.add(request);
    }

    /**
     * 获取系请求队列
     *
     * @return
     */
    public static RequestQueue getRequestQueue() {
        if (null != mRequestQueue) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }
    }

    public static SDCardImageLoader getSDCardImageLoader() {
        if (null != mSDCardImageLoader) {
            return mSDCardImageLoader;
        } else {
            throw new IllegalStateException("SDCardImageLoader not initialized");
        }
    }

    public static void init(Context context) {
        int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                .getMemoryClass();
        int cacheSize = 1024 * 1024 * memClass / 6;
        //内存缓存
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return getBitmapBytes(value);
            }

            @Override
            protected void entryRemoved(boolean evicted, String key,
                                        Bitmap oldValue, Bitmap newValue) {
                // 不要在这里强制回收oldValue，因为从LruCache清掉的对象可能在屏幕上显示着，
                // 这样就会出现空白现象
                super.entryRemoved(evicted, key, oldValue, newValue);
            }
        };
        //SD卡缓存
        File cacheDir = new File(FileCache.getImageCacheDir(context));
        try {
            mDiskLruCache = DiskLruCache.open(cacheDir, Utils.getVersionCode(context), 1, 150 * 1024 * 1024);
        } catch (IOException e) {
            ReduceLog.e("DiskLruCache open error" + e.getMessage());
        }
        mImageRequestQueue = Volley.newRequestQueue(context);
        mRequestQueue = Volley.newRequestQueue(context);
        mBitmapLruCache = new BitmapLruCache(cacheSize, context, mMemoryCache, mDiskLruCache);
        mImageLoader = new ImageLoader(mImageRequestQueue, mBitmapLruCache);
        mSDCardImageLoader = new SDCardImageLoader(ScreenUtils.getScreenW(), ScreenUtils.getScreenH(), mMemoryCache);
        mAvatarImageLoader = new ImageLoader(Volley.newRequestQueue(context), mBitmapLruCache);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    private static class BitmapHoneycombMR1 {
        static int getByteCount(Bitmap bitmap) {
            return bitmap.getByteCount();
        }
    }

    private static int getBitmapBytes(Bitmap bitmap) {
        int result;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            result = BitmapHoneycombMR1.getByteCount(bitmap);
        } else {
            result = bitmap.getRowBytes() * bitmap.getHeight();
        }
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + bitmap);
        }
        return result;
    }

}
